package zy.server;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zy.dao.BackendUserDao;
import zy.dao.DevUserDao;
import zy.dto.LoginDto;
import zy.entity.BackendUser;
import zy.entity.DevUser;
import zy.sessionUtil.SsionUtils;
import zy.vo.LoginVo;

import java.util.List;
import java.util.UUID;

@Service
public class LogingUserServer {
    @Autowired
    BackendUserDao backendUserDao;

    @Autowired
    DevUserDao devUserDao;

    public LoginVo Login(LoginDto loginDto) {
        LoginVo loginVo=new LoginVo();
        if (loginDto.getUserType()==1){
            BackendUser backendUser=new BackendUser();
            backendUser.setUserpassword(loginDto.getPassword());
            backendUser.setUsercode(loginDto.getUserName());
            List<BackendUser> backendUsers = backendUserDao.queryAllByLimit(backendUser);
            if (backendUsers.get(0)==null){
                throw new RuntimeException("账号或密码错误");
            }
            loginVo.setPassword(loginVo.getPassword());
            loginVo.setToken(loginVo.getToken());
            loginVo.setUserName(loginDto.getUserName());
            loginVo.setUserType(loginDto.getUserType());
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(UUID.randomUUID().toString().replace("-",""));
            stringBuffer.append("-"+backendUsers.get(0).getUsercode());
            stringBuffer.append("-"+backendUsers.get(0).getId());
            stringBuffer.append("-admin");
            stringBuffer.append("-"+System.currentTimeMillis());
            SsionUtils.setToken(stringBuffer.toString(),backendUsers.get(0));
            loginVo.setToken(stringBuffer.toString());
            return loginVo;
        }else if (loginDto.getUserType()==2){
            DevUser devUser=new DevUser();
            devUser.setDevpassword(loginDto.getPassword());
            devUser.setDevcode(loginDto.getUserName());
            List<DevUser> devUsers = devUserDao.queryAllByLimit(devUser);
            if (devUsers.get(0)==null){
                throw new RuntimeException("账号或密码错误");
            }
            loginVo.setPassword(loginVo.getPassword());
            loginVo.setToken(loginVo.getToken());
            loginVo.setUserName(loginDto.getUserName());
            loginVo.setUserType(loginDto.getUserType());
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(UUID.randomUUID().toString().replace("-",""));
            stringBuffer.append("-"+devUsers.get(0).getDevcode());
            stringBuffer.append("-"+devUsers.get(0).getId());
            stringBuffer.append("-dev");
            stringBuffer.append("-"+System.currentTimeMillis());
            SsionUtils.setToken(stringBuffer.toString(),devUsers.get(0));
            loginVo.setToken(stringBuffer.toString());
            return loginVo;
        }else {
            throw new RuntimeException("类型不对");
        }
    }
}
